package cn.jdemo.juc.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * (1) condition使用await()、signal()
 *
 * @description
 * @date 2020/12/4
 */
public class DemoCondition02 {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    private static Integer num01 = 0;
    private static Integer num02 = 0;

    public static void main(String[] args) {
        test01();
    }
    public static void test01(){
        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "_1:" + num01);//Thread-0_1:0
                System.out.println(Thread.currentThread().getName() + "_1:" + num02);//Thread-0_1:0
                if (num01 == 0){
                    condition.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println(Thread.currentThread().getName() + "_2:" + num01);//Thread-0_2:1
                System.out.println(Thread.currentThread().getName() + "_2:" + num02);//Thread-0_2:1
                lock.unlock();
            }
        }).start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2L);
                lock.lock();
                num01++;
                num02++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                condition.signal();
                lock.unlock();
            }

        }).start();
    }


}
